package com.dmxh.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import com.dmxh.api.SellerAPI;
import com.dmxh.result.Result;
import com.dmxh.result.ResultConstant;
import com.dmxh.service.SeckillGoodsService;
import com.dmxh.util.JwtUtil;
import com.dmxh.vo.UserVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/secKill")
public class SeckillGoodsController {

    @Autowired
    private SellerAPI sellerAPI;


    @Autowired
    private SeckillGoodsService seckillGoodsService;

    //预热
    @PostMapping("/redisHot")
    public Result redisHot() {
        seckillGoodsService.querySeckillBeforeTheEndGoods();
        return Result.ok();
    }

    @GetMapping("/getRedisSecKillData")
    @SentinelResource(value = "redisSecKill",blockHandler = "blockMethed")//前面是相当于映射路径名称(自定义)  降级逻辑方法名
    public Result getRedisSecKillData() {
        return Result.ok().setData(seckillGoodsService.getRedisSecKillData());
    }

    //编写降级方法
    public Result blockMethed(BlockException exception) {
        return Result.response(ResultConstant.SECKILL_QUERY_ERROR);//秒杀查询点击次数过多
    }

    @GetMapping("/getSeckillGoodsByGoodsId")
    public Result getSeckillGoodsByGoodsId(Long goodsId){
        return Result.ok().setData(seckillGoodsService.getSeckillGoodsByGoodsId(goodsId));
    }


    @GetMapping("/query")
    public Result query() {
        seckillGoodsService.common();
        System.out.println("query");
        return Result.ok().setData("query方法执行");
    }

    @GetMapping("/save")
    public Result save() {
        seckillGoodsService.common();
        System.out.println("save");
        return Result.ok().setData("save方法执行");
    }


    //熔断降级  如果超过响应时间   就会进入熔断逻辑  注意:如果没有调用数据库 那么  响应速度是极快的
    @GetMapping("/fallBack")
    public Result fallBack(Integer id) {
        if (Objects.equals(id, 2)) {//如果id不是2就不会超时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return Result.ok().setData(sellerAPI.queryByIdVoid(id));
    }
}
